package com.study.lxy.netty.bio;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerSocketHandler implements Runnable {

    private Socket socket;
    private static final Logger logger = LoggerFactory.getLogger(ServerSocketHandler.class);

    public ServerSocketHandler(Socket socket){
        this.socket = socket;
    }

    public void run() {
        BufferedReader br = null;
        PrintWriter pw = null;
        logger.info("received a connect");
        try {
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            logger.info("try to receive message");
            String line = br.readLine();
            logger.info("message received : {}" , line);
            pw = new PrintWriter(socket.getOutputStream(), true);
            pw.println("hello, " + line);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }

                if(pw != null){
                    pw.close();
                }
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
